﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Data;
using System.Collections;
using System.Drawing;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
using System.Data.OleDb;
using System.Configuration;
using System.Web.Script.Serialization;
using RenrenDotSDK;
using RenrenDotSDK.APIUtility;
using RenrenDotSDK.Model;
using JSONDecoder;


namespace WebApplication1
{
    public static class Consts
    {
        public const int SUCCESS = 1;
        public const int OPEN_FAILED = 100;
        public const int PROC_FAILED = 99;
    }

    /// <summary>
    /// RenRen related codes
    /// </summary>
    #region RENREN

    public class RenRen
    {
        public RenrenDotSDK.RenrenApiClient rr = null;
        string name = null;
        string ID = null;

        public  void Init()
        {
            if ( rr == null )
                rr = new RenrenApiClient();
        }

        public string GetUserName()
        {
                Init();
                string ResponseData = rr.CallMethodWithField("users.getInfo", "name");
                List<UserInfo> list = new JavaScriptSerializer().Deserialize<List<UserInfo>>(ResponseData);
                if (list == null)
                {
                    list = new List<UserInfo>();
                    list.Add(new UserInfo("error", ResponseData));
                }
                return list[0].Name;
        }

        public string GetUserID()
        {
                Init();
                string ResponseData = rr.CallMethodWithField("users.getInfo", "name");
                List<UserInfo> list = new JavaScriptSerializer().Deserialize<List<UserInfo>>(ResponseData);
                if (list == null)
                {
                    list = new List<UserInfo>();
                    list.Add(new UserInfo("error", ResponseData));
                } 
                return list[0].Uid;            
        }
    }

    #endregion

    /// <summary>
    /// 存放用户信息
    /// </summary>
    [Serializable] 
    public class UserInfo
    {
        public string Uid { set; get; }
        public string Name { set; get; }
        public string IconUrl { set; get; }

        public UserInfo() { }
        public UserInfo(string name, string ID)
        {
            Name = name;
            Uid = ID;
        }
        public UserInfo(string name, string ID, string Icon)
        {
            Name = name;
            Uid = ID;
            IconUrl = Icon;
        }

        public int CompareTo(object obj)
        {
            UserInfo b = obj as UserInfo;
            return this.Uid.CompareTo (b.Uid);
        }

        public override bool Equals(object obj)
        {
            return this.Uid==((UserInfo)obj).Uid;
        }
    }

    public partial class WebForm1 : System.Web.UI.Page
    {      

        // user list from RenRen
        public List<UserInfo> rrUserList = new List<UserInfo>();
        // user list from DB
        public List<UserInfo> userList = new List<UserInfo>();

        // RenRenAPI
        private RenRen renren = new RenRen();

        //声明调用DLL
        [DllImport("c:\\site\\face2.0.dll")]
        //功能是将根目录下的 in.jpg 处理成 result_in.jpg
        public static extern void main_proc(String a);

        // 检查一张照片是否被识别。返回01逻辑值
        [DllImport("c:\\site\\face2.0.dll")]
        public static extern int face_check(String a);

        // 检查一张照片是否被识别。返回01逻辑值
        [DllImport("c:\\site\\face2.0.dll")]
        public static extern int resize(String a);

        //合成项目名称
        string projectname;

        /// <summary>
        /// 图片相关 全局变量
        /// </summary>
        /// 

        protected string getUserName()
        {
            if (TextBoxUserName.Text == "")
                TextBoxUserName.Text = renren.GetUserName();
            return TextBoxUserName.Text;
        }
        protected string getUserID()
        {
            if (TextBoxUserID.Text == "")
                TextBoxUserID.Text = renren.GetUserID();
            return TextBoxUserID.Text;
        }


        /// <summary>
        /// 图片处理相关函数（用户方面）
        /// </summary>
        #region MainAlgo_user
        
        void CreateProjectDirectory()
        {
            if (!Directory.Exists(projectname))
                Directory.CreateDirectory(projectname);
            if (!Directory.Exists(Server.MapPath(projectname)))
                Directory.CreateDirectory(Server.MapPath(projectname));
        }


        /// <summary>
        /// 检查贴入fileupload中的照片是否被识别
        /// </summary>
        /// <returns>
        /// Consts.SUCCESS 1 识别
        /// Consts.PROC_FAILED 99 照片不识别
        /// Consts.OPEN_FAILED 100 照片打开失败
        /// </returns>
        int check( string filename )
        {
            Int32 ImageSize = FileUpload1.PostedFile.ContentLength;
            String ImageType = FileUpload1.PostedFile.ContentType;
            Stream ImageStream = FileUpload1.PostedFile.InputStream;
            Byte[] ImageContent = new Byte[ImageSize];

            // 初始化 stream
            ImageStream.Seek(0, SeekOrigin.Begin);
            ImageStream.Read(ImageContent, 0, ImageSize);

            // 清除上次的缓存
            if (File.Exists(filename+".ldm"))
                File.Delete(filename+".ldm");

            // 改变大小以及检查是否被识别
            resize(filename);
            int check_rst = face_check(filename);
            return check_rst;
        }

        protected bool checkDB(string entry, string item)
        {
            //连接数据库，准备插入新照片
            OleDbConnection con = new OleDbConnection(ConfigurationManager.ConnectionStrings["conStr"].ToString());
            String sql = "INSERT INTO users(ID, img, username) values(@ID, @img, @username)";
            OleDbCommand cmd = new OleDbCommand(sql, con);

            String check_exist = "SELECT count(*) FROM users WHERE " + entry + " = " + item;
            OleDbCommand cmd_check = new OleDbCommand(check_exist, con);

            con.Open();
            object count_id = cmd_check.ExecuteScalar();
            if ((int)count_id >= 1)
            {
                con.Close();
                return true;
            }
            con.Close();
            return false;
        }

        /// <summary>
        /// 将FileUpload中的 照片 与Text中的 ID 插入数据库
        /// </summary>
        /// <returns></returns>
        int write2DB(string filename)
        {

            System.IO.FileStream filestream = new FileStream(filename, FileMode.Open);
            Int32 ImageSize = (Int32)filestream.Length;
            Stream ImageStream = (Stream)filestream;
            Byte[] ImageContent = new Byte[ImageSize];

            // 初始化 stream
            ImageStream.Seek(0, SeekOrigin.Begin);
            ImageStream.Read(ImageContent, 0, ImageSize);


            //连接数据库，准备插入新照片
            OleDbConnection con = new OleDbConnection(ConfigurationManager.ConnectionStrings["conStr"].ToString());
            String sql = "INSERT INTO users(ID, img, username) values(@ID, @img, @username)";
            OleDbCommand cmd = new OleDbCommand(sql, con);

            String check_exist = "SELECT count(*) FROM users WHERE ID = " + getUserID();
            OleDbCommand cmd_check = new OleDbCommand(check_exist, con);

            con.Open();
            object count_id = cmd_check.ExecuteScalar();
            if ((int)count_id == 1)
            {
                cmd_check = new OleDbCommand("DELETE * FROM users WHERE ID = " + getUserID(), con);
                cmd_check.ExecuteNonQuery();
            }
            con.Close();

            //
            cmd.Parameters.AddWithValue("@ID", getUserID());
            cmd.Parameters.AddWithValue("@img", ImageContent);
            cmd.Parameters.AddWithValue("@username", getUserName());
            

            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
                CheckBoxListInit();
            }
            catch (OleDbException ex)
            {
                Response.Write("Insert Failed.Error Details are:" + ex.ToString());
                return -1;
            }
            return 0;
        }

        int clear_buf_file()
        {
            if (!Directory.Exists(projectname + "\\pic"))
            {
                Directory.CreateDirectory(projectname + "\\pic");
                return 0;
            }
            for (int i = 0; i < 100; i++)
            {
                File.Delete(projectname + "\\pic\\" + i.ToString("D2") + ".jpg.ldm");
                File.Delete(projectname + "\\pic\\" + i.ToString("D2") + ".jpg");
                File.Delete(projectname + "\\pic\\" + i.ToString("D2") + "_affined.jpg");
            }

            return 1;
        }

        /// <summary>
        /// 从数据库里读取用户信息
        /// </summary>
        /// <returns></returns>
        protected List<UserInfo> readUserInfo()
        {
            List<UserInfo> ret = new List<UserInfo>();

            OleDbConnection con = new OleDbConnection(ConfigurationManager.ConnectionStrings["conStr"].ToString());
            con.Open();

            String sql = "SELECT * FROM users";
            OleDbCommand cmd = new OleDbCommand(sql, con);

            OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

            while (reader.Read())
            {
                UserInfo entry = new UserInfo(reader["username"].ToString(), reader.GetInt32(0).ToString());
                ret.Add(entry);
            }
            return ret;
        }


        /// <summary>
        /// 将数据库内的照片粘贴到目录下
        /// </summary>
        protected void Paste_Pics()
        {
            OleDbConnection con = new OleDbConnection(ConfigurationManager.ConnectionStrings["conStr"].ToString());
            con.Open();
            Int32 counter = 0;

            for (int i = 0; i < CheckBoxList1.Items.Count; i++)
            {
                if (CheckBoxList1.Items[i].Selected)
                {

                    String sql = "SELECT img FROM users where ID=" + userList[i].Uid.ToString();
                    OleDbCommand cmd = new OleDbCommand(sql, con);

                    OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

                    if (reader.Read())
                    {
                        Byte[] ImageContent = (Byte[])reader["img"];

                        FileStream ImgFileStream = new FileStream(projectname + "\\pic\\" + counter.ToString("D2") + ".jpg", FileMode.Create);
                        BinaryWriter BinWri = new BinaryWriter(ImgFileStream);
                        counter++;

                        BinWri.Write(ImageContent);
                        BinWri.Close();
                        ImgFileStream.Close();
                    }
                }
            }
            con.Close();
        }


        /// <summary>
        /// 最终生成结果，储存到网页根目录下"final_result.jpg"
        /// </summary>
        /// <returns></returns>
        int generate_result()
        {
            // 清理之前的缓存  
            clear_buf_file();

            // 粘贴照片
            Paste_Pics();

            // 调用处理照片的程序
            main_proc(projectname);
            // 将dll生成的结果复制到 程序根目录下。
            if (!File.Exists(projectname + "\\final_result.jpg"))
            {
                return Consts.OPEN_FAILED;
            }
            if (File.Exists(Server.MapPath(projectname + "\\final_result.jpg")))
                File.Delete(Server.MapPath(projectname + "\\final_result.jpg"));
            if (!Directory.Exists(Server.MapPath(projectname)))
                Directory.CreateDirectory(Server.MapPath(projectname));
            File.Move(projectname + "\\final_result.jpg", Server.MapPath(projectname + "\\final_result.jpg"));

            return 1;
        }

        #endregion

        /// <summary>
        /// 图像处理相关函数（管理员）
        /// </summary>
        #region MainAlgo_admin

        /// <summary>
        /// 来自主网页，有改动
        /// </summary>
        /// <param name="Uids"></param>
        protected void Paste_Pics_admin(ArrayList Uids)
        {
            CreateProjectDirectory();

            OleDbConnection con = new OleDbConnection(ConfigurationManager.ConnectionStrings["conStr"].ToString());
            con.Open();
            Int32 counter = 0;

            foreach (string Uid in Uids)
            {
                String sql = "SELECT img FROM users where ID=" + Uid;
                OleDbCommand cmd = new OleDbCommand(sql, con);

                OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

                if (!Directory.Exists(projectname + "\\pic"))
                    Directory.CreateDirectory(projectname + "\\pic");

                if (reader.Read())
                {
                    Byte[] ImageContent = (Byte[])reader["img"];

                    FileStream ImgFileStream = new FileStream(projectname + "\\pic\\" + counter.ToString("D2") + ".jpg", FileMode.Create);
                    BinaryWriter BinWri = new BinaryWriter(ImgFileStream);
                    counter++;

                    BinWri.Write(ImageContent);
                    BinWri.Close();
                    ImgFileStream.Close();
                }
            }
            con.Close();
        }

        private ArrayList readFromFile_admin(string fileName)
        {
            FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            StreamReader reader = new StreamReader(fileStream);
            string line = null;
            ArrayList Uids = new ArrayList();
            // 读取projectName;
            projectname = reader.ReadLine();
            // 清空checkboxlist1
            CheckBoxList_admin.Items.Clear();
            //按行读取ID
            line = reader.ReadLine();
            while (line != null)
            {
                Uids.Add(line);
                CheckBoxList_admin.Items.Add(line);
                line = reader.ReadLine();
            }
            foreach (ListItem item in CheckBoxList_admin.Items)
            {
                item.Selected = true;
            }

            reader.Close();
            fileStream.Close();
            return Uids;
        }

        /// <summary>
        /// 来自主网页，有改动
        /// </summary>
        /// <returns></returns>
        int generate_result_admin(string fileName)
        {
            // 清理之前的缓存  
            clear_buf_file();

            //读取project
            ArrayList Uids = readFromFile_admin("order_list\\" + fileName);

            // 粘贴照片
            Paste_Pics_admin(Uids);

            // 调用处理照片的程序
            main_proc(projectname);
            // 将dll生成的结果复制到 程序根目录下。
            if (!File.Exists(projectname + "\\final_result.jpg"))
            {
                return Consts.OPEN_FAILED;
            }
            if (File.Exists(Server.MapPath(projectname + "\\final_result.jpg")))
                File.Delete(Server.MapPath(projectname + "\\final_result.jpg"));
            if (!Directory.Exists(Server.MapPath(projectname)))
                Directory.CreateDirectory(Server.MapPath(projectname));
            File.Move(projectname + "\\final_result.jpg", Server.MapPath(projectname + "\\final_result.jpg"));

            return 1;
        }


        protected void process(string fileName)
        {

            // 调用处理照片的程序
            int rst = generate_result_admin(fileName);


            switch (rst)
            {
                case Consts.OPEN_FAILED:
                    Response.Write("结果读取失败");
                    break;
                case Consts.PROC_FAILED:
                    Response.Write("处理过程出错");
                    break;
                case Consts.SUCCESS:
                    Response.Write("<script>confirm('处理成功！')</script>");
                    Response.Write("处理成功！");
                    break;
                default:
                    Response.Write("处理结果未知错误");
                    break;
            }
            //                ImageResult.ImageUrl = projectname + "\\final_result.jpg";
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            
            // 项目信息
            projectname = TextBoxProjectName.Text;
            renren.Init();

            // 载入用户信息
            userList.Clear();
            userList = readUserInfo();

            if (!IsPostBack)
            {
                {
                    string tmpname = getUserName();
                    if (tmpname == "error")
                        Response.Write(getUserID());
                    // record visitors
                    FileStream filestream = new FileStream("visitors.dat", FileMode.Append, FileAccess.Write);
                    StreamWriter writer = new StreamWriter(filestream);
                    writer.WriteLine(getUserName() + "," + getUserID() + "," + DateTime.Now.ToString());
                    writer.Close();
                    filestream.Close();
                }
                //创建pic目录
                if (!Directory.Exists(projectname + "\\pic"))
                    Directory.CreateDirectory(projectname + "\\pic");
                for (int i = 0; i < 100; i++)
                {
                    File.Delete(projectname + "\\pic\\" + i.ToString("D2") + ".jpg.ldm");
                    File.Delete(projectname + "\\pic\\" + i.ToString("D2") + ".jpg");
                }
                if (File.Exists(Server.MapPath(projectname + "\\check_face.jpg")))
                    File.Delete(Server.MapPath(projectname + "\\check_face.jpg"));
                if (File.Exists(projectname + "\\check_face.jpg"))
                    File.Move(projectname + "\\check_face.jpg", Server.MapPath(projectname + "\\check_face.jpg"));
                
                //欢迎界面
                MultiView1.SetActiveView(MultiView1.Views[0]);
                if (Request["action"] == "get_result")
                {
                    MultiView1.SetActiveView(MultiView1.Views[4]);
                }

                // 装载项目名称，判断是否可以查看项目结果
                string[] fileNames = Directory.GetFiles("order_list");
                ListBoxProjCus.Items.Clear();
                ListBoxProjNames.Items.Clear();
                foreach (string fileName in fileNames)
                {
                    FileStream fileStream = new FileStream(fileName, FileMode.Open);
                    StreamReader reader = new StreamReader(fileStream);
                    projectname = reader.ReadLine();
                    reader.Close();
                    fileStream.Close();

                    ArrayList Uids = readFromFile_admin(fileName);

                    if (Uids.Contains(getUserID()))
                    {
                        if (File.Exists(Server.MapPath(projectname + "\\final_result.jpg")))
                            ListBoxProjCus.Items.Add(new ListItem(projectname + "（已完成）"));
                        else
                            ListBoxProjCus.Items.Add(new ListItem(projectname + "（等待中）"));
                        ListBoxProjNames.Items.Add(new ListItem(projectname));
                    }
                }
                if (ListBoxProjCus.Items.Count > 0)
                    Bn_Result.Visible = true;
            }

        }


        //    // 存放每个checkbox对应的ID
        //List<string> checkboxID = new List<string>();

        // 初始化CheckBox 显示数据库内容
        protected void CheckBoxListInit()
        {
            // 存放用户信息
            ///////////本地ID
            OleDbConnection con = new OleDbConnection(ConfigurationManager.ConnectionStrings["conStr"].ToString());
            String sql = "SELECT * FROM users";
            OleDbCommand cmd = new OleDbCommand(sql, con);

            con.Open();
            OleDbDataReader reader = cmd.ExecuteReader();

            DataSet userData = new DataSet();
            OleDbDataAdapter adapter = new OleDbDataAdapter(sql, con);

            ////databind 方法
            //CheckBoxList1.DataSource = reader;
            //CheckBoxList1.DataTextField = "username";
            //CheckBoxList1.DataBind();

            //本地数据库的用户
            List<UserInfo> dbUsers = new List<UserInfo>();
            while( reader.Read() ){
                UserInfo user = new UserInfo( reader["username"].ToString(), reader["ID"].ToString());
                dbUsers.Add( user );
            }

            // RenRen API
            string responseData = renren.rr.CallMethod("friends.getFriends");
            List<Friend> list = new JavaScriptSerializer().Deserialize<List<Friend>>(responseData);

            foreach (Friend f in list)
            {
                rrUserList.Add(new UserInfo(f.Name, f.Id, "<img src=\"" + f.Tinyurl + "\" />"));
                f.Tinyurl = "<img src=\"" + f.Tinyurl + "\" />" + f.Name + f.Id;

            }

            //CheckBoxList3.DataSource = list;
            //CheckBoxList3.DataTextField = "Tinyurl";
            //CheckBoxList3.DataBind();

            CheckBoxList2.DataSource = rrUserList;
            CheckBoxList2.DataTextField = "Uid";
            CheckBoxList2.DataBind();

            //// 清空checkbox ID对应关系
            //checkboxID.Clear();

            // 动态增删 求好友列表与本地数据库的交集
            CheckBoxList1.Items.Clear();
            CheckBoxList3.Items.Clear();
            CheckBoxList1.Items.Add(new ListItem("我自己"));
            CheckBoxList3.Items.Add(new ListItem(getUserID()));
            foreach (UserInfo user in dbUsers)
            {
                if ( rrUserList.Contains( user )){
                    ListItem item = new ListItem();
                    foreach (UserInfo u in rrUserList)
                    {
                        if (u.Equals(user))
                        {

                            // 辅助控件，用来保存ID；
                            item = new ListItem(u.Uid);
                            CheckBoxList3.Items.Add(item);

                            // 显示的控件，用来交互
//                            item = new ListItem(u.Name+"<br>"+u.IconUrl+"<br><br>");
                            item = new ListItem(u.Name);
                            CheckBoxList1.Items.Add(item);
                            break;
                        }
                    }
                }
            }

            reader.Close();
            con.Close();

        }

        // 上传按钮
        protected void Bn_Upload_Click(object sender, EventArgs e)
        {
            if (Request["action"] == "IAmGLY")
            {
                MultiView1.SetActiveView(MultiView1.Views[7]);
                return;
            }

            if (!FileUpload1.HasFile)
            {
                Response.Write("<script>alert('请选择本地图片')</script>");
                return;
            }

            Int32 ImageSize = FileUpload1.PostedFile.ContentLength;
            String ImageType = FileUpload1.PostedFile.ContentType;
            Stream ImageStream = FileUpload1.PostedFile.InputStream;
            Byte[] ImageContent = new Byte[ImageSize];

            // 初始化 stream
            ImageStream.Seek(0, SeekOrigin.Begin);
            ImageStream.Read(ImageContent, 0, ImageSize);

            // 临时照片文件名
            string filename = getUserID() + "upload_face.jpg";

            // 删除上次的照片
            if (File.Exists(filename))
                File.Delete(filename);

            // 创建临时照片文件
            FileStream ImgFileStream = new FileStream(filename, FileMode.Create);
            BinaryWriter BinWri = new BinaryWriter(ImgFileStream);
            BinWri.Write(ImageContent);
            BinWri.Close();
            ImgFileStream.Close();

            // 显示
            if (File.Exists(Server.MapPath(filename)))
                File.Delete(Server.MapPath(filename));
            File.Copy(filename, Server.MapPath(filename));
            
            //检查是否被识别
            int check_rst = check(filename);
 
            if (check_rst == Consts.PROC_FAILED)
            {
                Response.Write("<script>alert('请更换图片')</script>");
                return;
            }
            else if (check_rst == Consts.OPEN_FAILED)
            {
                Response.Write("<script>alert('图片读取错误')</script>");
                return;
            }
            else
            {
                write2DB(filename);
                Response.Write("<script>alert('照片已添加')</script>");
                //show uploaded img
                Image1.ImageUrl = filename;
                MultiView1.SetActiveView(MultiView1.Views[2]);

            }
        }

        // 合成按钮
        protected void Bn_Generate_Click(object sender, EventArgs e)
        {
            // project name
            if (TextBoxProjectName.Text == "")
            {
                Response.Write("<script>alert('亲，给这个宏伟的项目起个名字吧~')</script>");
            }
            else
            {

                // 项目名称
                projectname = TextBoxProjectName.Text;

                // 在磁盘上建立项目目录
                CreateProjectDirectory();

                // 跳转页面
                MultiView1.SetActiveView(MultiView1.Views[3]);

            }

            // process
            if (Ctr_Online.Checked) // on-line mode
            {
                // 调用处理照片的程序
                int rst = generate_result();


                switch (rst)
                {
                    case Consts.OPEN_FAILED:
                        Response.Write("结果读取失败");
                        break;
                    case Consts.PROC_FAILED:
                        Response.Write("处理过程出错");
                        break;
                    case Consts.SUCCESS:
                        Response.Write("<script>confirm('处理成功！')</script>");
                        Response.Write("处理成功！");
                        break;
                    default:
                        Response.Write("处理结果未知错误");
                        break;
                }
                MultiView1.SetActiveView(MultiView1.Views[4]);
                ImageResult.ImageUrl = projectname + "\\final_result.jpg";
            }
            else   // off-line mode
            {

                // id文件
                DateTime cur = DateTime.Now;
                string filename = cur.Year.ToString("D4") + cur.Month.ToString("D2") + cur.Day.ToString("D2") + cur.Millisecond.ToString();
                FileStream orderFile = new FileStream("order_list\\"+filename +".uid", FileMode.Create, FileAccess.Write);
                StreamWriter writer = new StreamWriter(orderFile);
                writer.WriteLine(projectname);

                for (int i = 0; i < CheckBoxList1.Items.Count; i++)
  //                  if (CheckBoxList1.Items[i].Selected)
                    {
                        writer.WriteLine(CheckBoxList3.Items[i].Text);
                    }
                writer.Close();
                orderFile.Close();
                MultiView1.SetActiveView(MultiView1.Views[6]);
            }
        }


        /// <summary>
        /// 清空数据库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        protected void Clear_Db(object sender, EventArgs e)
        {
            OleDbConnection con = new OleDbConnection(ConfigurationManager.ConnectionStrings["conStr"].ToString());
            String sql = "delete * FROM users";
            OleDbCommand cmd = new OleDbCommand(sql, con);

            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
            CheckBoxListInit();
        }

        /// <summary>
        /// 欢迎按钮点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void On_WelButton_Clicked(object sender, EventArgs e)
        {
            MultiView1.SetActiveView(MultiView1.Views[1]);
        }

        protected void Button2_Click1(object sender, EventArgs e)
        {
            MultiView1.SetActiveView(MultiView1.Views[1]);
        }

        protected void On_Bn_Next_Click(object sender, EventArgs e)
        {
            MultiView1.SetActiveView(MultiView1.Views[3]);
            CheckBoxListInit();
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            MultiView1.SetActiveView(MultiView1.Views[2]);
        }


        protected void upload_1_Load(object sender, EventArgs e)
        {
//            TextBox1.Text = getUserID();
        }

        protected void Button1_Click1(object sender, EventArgs e)
        {
            MultiView1.SetActiveView(MultiView1.Views[2]);
        }

        protected void Button_Next2_Click(object sender, EventArgs e)
        {
            if (TextBoxProjectName.Text == "")
            {
                Response.Write("<script>alert('亲，给这个宏伟的项目起个名字吧~')</script>");
            }
            else
            {

                // 项目名称
                projectname = TextBoxProjectName.Text;

                // 在磁盘上建立项目目录
                CreateProjectDirectory();

                // 跳转页面
                MultiView1.SetActiveView(MultiView1.Views[3]);

            }
        }


        #region 管理员界面

        protected void ButtonNext_Click(object sender, EventArgs e)
        {
            projectname = ListBox_admin.SelectedItem.ToString();
            generate_result_admin(projectname + ".uid");
            Response.Clear();

            // 项目名称
            Response.Write("<p>" + projectname + "</p>");
            // 最终结果
            Response.Write("<img src=\"" + projectname + "\\final_result.jpg\" />");
            // 分项
            Response.Write("<br> <table> <tr>");

            Directory.CreateDirectory(Server.MapPath(projectname + "\\pic"));
            for (int i = 0; i < 100; i++)
            {
                string fn = projectname + "\\pic\\" + i.ToString("D2") + "_affined.jpg";
                if (!File.Exists(fn))
                    break;
                Response.Write("<td> <img src=\"" + fn + "\" width = '200px'  /> ");
                Response.Write("<br>" + CheckBoxList_admin.Items[i].ToString() + "</td>");
                File.Delete(Server.MapPath(fn));
                File.Copy(fn, Server.MapPath(fn));
            }
            Response.Write("</tr> </table>");
        }

        protected void ButtonRewrite_Click(object sender, EventArgs e)
        {
            projectname = ListBox_admin.SelectedItem.ToString();
            FileStream orderFile = new FileStream("order_list\\" + projectname + ".uid", FileMode.Create, FileAccess.Write);
            StreamWriter writer = new StreamWriter(orderFile);
            writer.WriteLine(projectname);

            for (int i = 0; i < CheckBoxList_admin.Items.Count; i++)
                if (CheckBoxList_admin.Items[i].Selected)
                {
                    writer.WriteLine(CheckBoxList_admin.Items[i].Text);
                }
            writer.Close();
            orderFile.Close();
        }

        protected void ButtonFinish_Click(object sender, EventArgs e)
        {
            string msg = "您的合成请求已经完成，请登录应用查看结果！谢谢！";
            foreach (ListItem item in CheckBoxList_admin.Items)
            {
                renren.rr.SendMessage(item.ToString(), msg);
            }
            File.Move("order_list\\" + projectname + ".uid", "finished_order\\" + projectname + ".uid");
        }

        public List<string> projList = new List<string>();
        protected void AdminView6_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string[] fileNames = Directory.GetFiles("order_list");
                ListBox_admin.Items.Clear();
                foreach (string fileName in fileNames)
                {
                    FileStream fileStream = new FileStream(fileName, FileMode.Open);
                    StreamReader reader = new StreamReader(fileStream);
                    projList.Add( reader.ReadLine() );
                    reader.Close();
                    fileStream.Close();
                    string itemName = Path.GetFileNameWithoutExtension(fileName);
                    ListBox_admin.Items.Add(new ListItem(itemName));
                    

                }
            }
        }

        protected void Button3_Click(object sender, EventArgs e)
        {
            MultiView1.SetActiveView(MultiView1.Views[6]);
        }

        protected void AdminView6_Activate(object sender, EventArgs e)
        {
            // 打开管理员列表
            {

                renren.Init();

                string fileName = Server.MapPath("AdminList.dat");
                FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                StreamReader reader = new StreamReader(fileStream);
                ArrayList Uids = new ArrayList();
                string line = null;
                //按行读取ID
                line = reader.ReadLine();
                while (line != null)
                {
                    Uids.Add(line);
                    line = reader.ReadLine();
                }
                reader.Close();
                fileStream.Close();

                if (!Uids.Contains(getUserID()))
                {
                    Response.Write("你无权查看本页面,请自觉退出");
                    MultiView1.SetActiveView(MultiView1.Views[1]);
                }
            }

        }

        #endregion


        protected void View5_Activate(object sender, EventArgs e)
        {
            
        }

        protected void upload_1_Activate(object sender, EventArgs e)
        {
            ImageBack.ImageUrl = "webimg/upload_back.png";
            if (checkDB( "ID", getUserID()))
            {
                OleDbConnection con = new OleDbConnection(ConfigurationManager.ConnectionStrings["conStr"].ToString());
                con.Open();
                String sql = "SELECT img FROM users where ID=" + getUserID();
                OleDbCommand cmd = new OleDbCommand(sql, con);

                OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

                if (reader.Read())
                {
                    Byte[] ImageContent = (Byte[])reader["img"];

                    FileStream ImgFileStream = new FileStream(getUserID()+ "upload_face.jpg", FileMode.Create);
                    BinaryWriter BinWri = new BinaryWriter(ImgFileStream);

                    BinWri.Write(ImageContent);
                    Image4.ImageUrl=getUserID()+"upload_face.jpg";
                    BinWri.Close();
                    ImgFileStream.Close();

                    bn_skip.Visible = true;
                }
                con.Close();
            }
        }

        protected void uploadSuccess_2_Activate(object sender, EventArgs e)
        {
            Image1.ImageUrl = getUserID() + "upload_face.jpg";
            ImageBack.ImageUrl = "webimg/upload_back.png";
        }

        protected void select_3_Activate(object sender, EventArgs e)
        {
            CheckBoxListInit();
            ImageBack.ImageUrl = "webimg/invite_back.png";
        }

        protected void View6_Activate(object sender, EventArgs e)
        {
            ImageBack.ImageUrl = "webimg/finished_back.png";
        }

        protected void select_3_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DateTime cur = DateTime.Now;
                TextBoxProjectName.Text = getUserName() + "的人脸合成计划(" + cur.Month.ToString() + "月" + cur.Day.ToString() + "日)";
            }
        }

        protected void Bn_Skip_Click(object sender, ImageClickEventArgs e)
        {
            MultiView1.SetActiveView(MultiView1.Views[2]);
        }

        protected void Button_share_Click(object sender, ImageClickEventArgs e)
        {
            int ind = ListBoxProjCus.SelectedIndex;
            Response.Write(Server.MapPath(ListBoxProjNames.Items[ind] + "\\final_result.jpg"));
            Response.Write( renren.rr.UploadPhoto( Server.MapPath( ListBoxProjNames.Items[ind] + "\\final_result.jpg"), "用Mr.Mix合成的人脸像") );
        }

        protected void result_4_Activate(object sender, EventArgs e)
        {
            if (Request["name"] == "")
                Response.Write("<script>alert('错误：project name == null ')</script>");
            return;
            ArrayList Uids = readFromFile_admin(Request["name"]);
            //if (!Uids.Contains(getUserID()))
            //{
            //    Response.Write("<script>alert('项目名错误')</script>");
            //    Response.Redirect(ConfigurationManager.ConnectionStrings["CallBack"].ToString());
            //    return;
            //}
 
           ImageResult.ImageUrl = Request["pn"] + "\\final_result.jpg";
            Response.Write("<img src=\"" + projectname + "\\final_result.jpg\" />");
        }

        protected void Bn_Result_Click(object sender, ImageClickEventArgs e)
        {
            if (Request["action"] == "IAmGLY")
            {
                MultiView1.SetActiveView(MultiView1.Views[7]);
                return;
            }

            MultiView1.SetActiveView(MultiView1.Views[5]);
        }

        protected void Bn_New_Click(object sender, ImageClickEventArgs e)
        {
            MultiView1.SetActiveView(MultiView1.Views[1]);
        }

        protected void Button_Next2_Click(object sender, ImageClickEventArgs e)
        {
            int ind = ListBoxProjCus.SelectedIndex;
            if (File.Exists(Server.MapPath(ListBoxProjNames.Items[ind] + "\\final_result.jpg")))
                ImageResult.ImageUrl = ListBoxProjNames.Items[ind] + "\\final_result.jpg";
            else
                ImageResult.ImageUrl = "webimg\\qphoto.png";
            MultiView1.SetActiveView(MultiView1.Views[4]);
        }

        protected void ProjCust5_Load(object sender, EventArgs e)
        {

        }

        protected void ListBox_admin_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }

        protected void Button1_Click2(object sender, EventArgs e)
        {
            Response.Write(ListBox_admin.SelectedItem.Text);
            readFromFile_admin(("order_list\\"+ListBox_admin.SelectedItem.Text+".Uid"));
        }

    }
}